# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : AosSanic
@file: OAClient
@Author: mengying
@email: 652044581@qq.com
@date: 2022/4/3 10:20
@desc: O2OA的获取token和登录人员信息等
========================================================================================================================
"""
from config import config
import requests, json
from o2oa.OAError import O2OAError


class O2OAClient:
    """O2OA常用的公共的方法"""

    def __init__(self):

        if hasattr(config, "O2OA_USER"):
            raise O2OAError("请在config 中配置O2OA_USER， O2OA_PWD， O2OA_URL")

        self.user = config.O2OA_USER
        self.password = config.O2OA_PWD
        self.headers = {"Content-Type": "application/json; charset=utf-8", }

    @property
    def o2oa_headers(self):
        self.headers["x-token"] = self._get_token()
        return self.headers

    def _get_token(self) -> str:
        """默认用户登录o2oa获取token"""
        url = config.O2OA_URL + "/x_organization_assemble_authentication/jaxrs/authentication"
        data = {'credential': self.user, 'password': self.password}
        response = requests.post(url, data=json.dumps(data), headers=self.headers).json()

        # 判断是否请求成功
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response["data"]["token"]

    def user_login(self, username, password):
        """指定用户登录获取token"""
        url = config.O2OA_URL + "/x_organization_assemble_authentication/jaxrs/authentication"
        data = {'credential': username, 'password': password}
        response = requests.post(url, data=json.dumps(data), headers=self.headers).json()

        # 判断是否请求成功
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response["data"]

    def user_info(self):
        url = config.O2OA_URL + "/x_organization_assemble_authentication/jaxrs/authentication"
        self.headers["x-token"] = self._get_token()
        response = requests.get(url, headers=self.headers).json()

        # 判断是否请求成功
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response["data"]


if __name__ == '__main__':
    print(O2OAClient().user_login("mengying", "123456"))